﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BackupObjects;
using BackupWebRole.MVCHelpers;
using System.IO;
using System.Web.Security;

namespace BackupWebRole.Areas.Backup.Controllers
{
    [Authorize]
    public class BackupController : Controller
    {
        //
        // GET: /Backup/Backup/

        public ActionResult Index()
        {
            BackupRepository br = new BackupRepository();
            br.LoadAll(this.User.Identity.Name);
            foreach (var item in br.Backups)
            {
                string icoextension = Path.GetExtension(item.OriginalFileName).Replace(".", "");
                //TODO: find the relative paths
                string FileIco =
                    Server.MapPath("~/icos/" +
                                   item.icofilename);

                if (!System.IO.File.Exists(FileIco))
                {
                    var src = br.GetBackupStreamIco(item.ID, User.Identity.Name);
                    if (src == null)
                    {
                        //TODO: log
                        break;
                    }


                    using (FileStream dest = System.IO.File.Create(FileIco))
                    {
                        int readCount;
                        var buffer = new byte[8192];
                        while ((readCount = src.Read(buffer, 0, buffer.Length)) != 0)
                            dest.Write(buffer, 0, readCount);

                    }
                }
            }
            return View(br);
        }
        public ActionResult Create()
        {
            return View(new BackupObject());
        }
        [HttpPost]
        public ActionResult Create(BackupObject bo, HttpPostedFileBase backupcontent)
        {

            if (backupcontent == null)
            {
                ModelState.AddModelError("Contents", " must upload a file");
            }
            Action a = () =>
            {
                using (BinaryReader read = new BinaryReader(backupcontent.InputStream))
                {
                    bo.Contents = read.ReadBytes(backupcontent.ContentLength);
                }
                bo.UploadBy = Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString();
                bo.OriginalFileName = backupcontent.FileName;
                
                BackupRepository br = new BackupRepository();
                br.Save(bo);

            };

            return a.TryCatch( RedirectToAction("Index"),View(bo),ModelState);
        }
        private ActionResult FromId(string id)
        {
            Func<BackupObject> a = () =>
            {
                BackupRepository br = new BackupRepository();
                var obj = br.Load(Guid.Parse(id), User.Identity.Name);
                if (obj == null)
                    throw new KeyNotFoundException("not found :" + id);
                return obj;

            };
            //TODO : add keynotfound
            return a.TryCatch(ret => View(ret), View("KeyNotFound", id), ModelState);
        }
        [HttpPost]
        public ActionResult Delete(string id)
        {
            Action a = () =>
                           {
                               BackupRepository br = new BackupRepository();
                               br.Delete(Guid.Parse(id), User.Identity.Name);
                           };
            return a.TryCatchJson();

        }
        public ActionResult Details(string id)
        {
            
            return FromId(id);
            
        }
        public ActionResult ViewDetails(string id)
        {


            BackupRepository br = new BackupRepository();
            var obj = br.Load(Guid.Parse(id), User.Identity.Name);
            if (obj == null)
                throw new ArgumentException(id, "id");

            var ret = new FileStreamResult(br.GetBackupStream(Guid.Parse(id), User.Identity.Name),
                                           "application/octet-stream");
            ret.FileDownloadName = obj.OriginalFileName;
            return ret;
        }
    }
}
